package com.gpay.erp.web.control;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import com.gpay.erp.core.dao.page.PageHelper;
import com.gpay.erp.core.dao.page.PagerModel;
import com.gpay.erp.core.system.bean.SysRole;
import com.gpay.erp.core.system.bean.SysUser;
import com.gpay.erp.core.system.bean.RoleTree;
import com.gpay.erp.services.system.RoleInteface;
import com.gpay.erp.web.util.WebUtil;
import com.gpay.erp.web.vo.ResponseInfo;
import com.gpay.erp.web.vo.UserSessionInfor;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.support.RequestContext;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

/**
 * 角色管理
 * 
 * @author lg
 * 
 */

@Controller
@RequestMapping("/roleController/")
public class RoleController extends BaseController {
	private Log log = LogFactory.getLog(RoleController.class);
	@Autowired
	private RoleInteface roleService;

	// 页面跳转 角色管理
	@RequestMapping("roleMenu")
	public String role() {
		return "system/role/roleMenu";
	}

	// 页面跳转 角色新增
	@RequestMapping("roleAdd")
	public String addRole() {
		return "system/role/roleAdd";
	}

	// 页面跳转 角色修改
	@RequestMapping("roleUpdate")
	public String updateRole(String id, ModelMap modelMap) {
		modelMap.addAttribute("roleId", id);
		return "system/role/roleUpdate";
	}

	// 页面跳转 角色授权
	@RequestMapping("roleGrant")
	public String grantRole(String id, ModelMap modelMap) {
		modelMap.addAttribute("roleId", id);
		return "system/role/roleGrant";
	}

	// 页面跳转 分配员工
	@RequestMapping("distributeUser")
	public String distributeUser(String id, ModelMap modelMap) {
		modelMap.addAttribute("roleId", id);
		return "system/role/roleDistribute";
	}

	/*
	 * 点击角色管理，返回角色分页数据
	 * 
	 * @param pageHelper
	 * 
	 * @param request
	 * 
	 * @param response
	 */
	@RequestMapping("roleManage")
	public void roleManage(PagerModel pagerModel, SysRole sysRole,
			PageHelper pageHelper, HttpServletRequest request,
			HttpServletResponse response) {
		RequestContext requestContext = new RequestContext(request);
		ResponseInfo responseInfo = new ResponseInfo();
		/* 当前页 */
		int pagenow = pageHelper.getPage();
		/* 每页显示记录数 */
		int rows = pageHelper.getRows();
		/* 分页信息填充进入PagerModel中 */
		sysRole.setPageSize(rows);
		sysRole.setFromRow((pagenow - 1) * rows);
		sysRole.setToRow(pagenow * rows);
		/* 查询数据，返回PagerModel */
		pagerModel = roleService.selectPageList(sysRole);
		if (pagerModel.getRows().size() > 0) {
			responseInfo.setResult("11000");
			responseInfo.setMessage(requestContext
					.getMessage("rolecode.available"));
		}
		responseInfo.setObject(pagerModel);
		WebUtil.responseToJson(response, responseInfo);
	}

	/*
	 * 角色权限资源树,用于勾选权限赋予角色
	 * 
	 * @param sysRole
	 * 
	 * @param request
	 * 
	 * @param response
	 */
	@RequestMapping("rolesTree")
	public void RoleTree(SysRole sysRole, HttpServletRequest request,
			HttpServletResponse response) {
		RequestContext requestContext = new RequestContext(request);
		ResponseInfo responseInfo = new ResponseInfo();
		if (sysRole.getId() != null || sysRole.getId() != "") {
			List list = roleService.findRoleMenu(sysRole);
			if (list.size() > 0) {
				responseInfo.setResult("10010");
				responseInfo.setMessage(requestContext
						.getMessage("privilege.menu.success"));
			}
			responseInfo.setObject(list);
		} else {
			responseInfo.setResult("10011");
			responseInfo.setMessage(requestContext
					.getMessage("privilege.menu.failed"));
		}
		WebUtil.responseToJson(response, responseInfo);
	}

	/*
	 * 点击新增按钮，执行角色新增操作/权限设置按钮
	 * 
	 * @param sysRole
	 * 
	 * @param roleTree 勾选的权限资源id
	 * 
	 * @param request
	 * 
	 * @param response
	 */
	@RequestMapping("addRole")
	public void addRole(SysRole sysRole, HttpServletRequest request,
			HttpServletResponse response) {
		RoleTree roleTree = new RoleTree();
		if (request.getParameterValues("choiceId[]") != null) {
			roleTree.setChoiceId(request.getParameterValues("choiceId[]"));
			roleTree.setRoleId(sysRole.getId());
		} else if(request.getParameter("choiceId")!=null){
			roleTree.setChoiceId(request.getParameter("choiceId").split(","));
			roleTree.setRoleId(sysRole.getId());
		}
		RequestContext requestContext = new RequestContext(request);
		ResponseInfo responseInfo = new ResponseInfo();
		HttpSession session = request.getSession();
		/* 获取登录的用户信息 */
		SysUser loginUser = (SysUser) session.getAttribute("loginUser");
		/* 设置日期格式 */
		SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		/* 获取当前是时间 */
		sysRole.setCreateDate(df.format(new Date()));
		sysRole.setUserName(loginUser.getUserName());
		if (roleTree.getRoleId() == null) {
			int flag = 0;
			/* 先建立角色后再赋予权限 */
			int id = roleService.insert(sysRole);
			if (id != 0) {
				log.info("插入记录后的id值为：" + id);

				if (roleTree.getChoiceId() != null) {
					roleTree.setRoleId(id + "");
					/* 分配角色资源 */
					flag = roleService.inserts(roleTree);
					if (flag != 0) {
						responseInfo.setResult("00040");
						responseInfo.setMessage(requestContext
								.getMessage("add.success"));
					} else {
						responseInfo.setResult("00041");
						responseInfo.setMessage(requestContext
								.getMessage("add.fail"));
					}
				}
			} else {
				responseInfo.setResult("00041");
				responseInfo.setMessage(requestContext.getMessage("add.fail"));
			}
		} else {
			/* 删除原有的资源权限 */
			int delId = roleService.delete(roleTree);
			if (delId != -1) {
				log.info("删除" + delId + "条数据");
			} else {
				log.info("删除失败");
			}
			/* 新增已勾选的资源权限 */
			int flag = roleService.inserts(roleTree);
			if (flag != 0) {
				responseInfo.setResult("00040");
				responseInfo.setMessage(requestContext
						.getMessage("add.success"));
			} else {
				responseInfo.setResult("00041");
				responseInfo.setMessage(requestContext.getMessage("add.fail"));
			}
		}
		WebUtil.responseToJson(response, responseInfo);
	}

	/*
	 * 点击明细，根据ID查看角色详细信息
	 * 
	 * @param sysRole
	 * 
	 * @param request
	 * 
	 * @param response
	 */
	@RequestMapping("detailRole")
	public void detailRole(PagerModel pagerModel,
			@ModelAttribute("sysRole") SysRole sysRole,
			HttpServletRequest request, HttpServletResponse response) {
		RequestContext requestContext = new RequestContext(request);
		ResponseInfo responseInfo = new ResponseInfo();
		/* 获取前端传入的id,判断是否为null */
		if (sysRole.getId() != null) {
			/* 根据ID查询明细 */
			pagerModel = roleService.selectById(sysRole.getId());
			responseInfo.setResult("00010");
			responseInfo
					.setMessage(requestContext.getMessage("select.success"));
		} else {
			responseInfo.setResult("00011");
			responseInfo.setMessage(requestContext.getMessage("select.fail"));
		}
		responseInfo.setObject(pagerModel);
		WebUtil.responseToJson(response, responseInfo);
	}

	/*
	 * 点击修改按钮，执行角色信息修改操作
	 * 
	 * @param sysRole
	 * 
	 * @param request
	 * 
	 * @param response
	 */
	@RequestMapping("updateRole")
	public void updateRole(SysRole sysRole, HttpServletRequest request,
			HttpServletResponse response) {
		RequestContext requestContext = new RequestContext(request);
		ResponseInfo responseInfo = new ResponseInfo();
		HttpSession session = request.getSession();
		/* 获取登录的用户信息 */
		SysUser loginUser = (SysUser) session.getAttribute("loginUser");
		/* 设置日期格式 */
		SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		/* 获取当前是时间 */
		sysRole.setCreateDate(df.format(new Date()));
		sysRole.setUserName(loginUser.getUserName());
		if (sysRole.getId() != null) {
			/* 执行角色修改操作 */
			int flag = roleService.update(sysRole);
			if (flag != 0) {
				log.info("修改记录的id值为：" + flag);
				responseInfo.setResult("00030");
				responseInfo.setMessage(requestContext
						.getMessage("update.success"));
			} else {
				responseInfo.setResult("00031");
				responseInfo.setMessage(requestContext
						.getMessage("update.fail"));
			}
		} else {
			responseInfo.setResult("00031");
			responseInfo.setMessage(requestContext.getMessage("update.fail"));
		}
		WebUtil.responseToJson(response, responseInfo);
	}

	/*
	 * 点击删除，根据id删除所选角色，可批量删除
	 * 
	 * @param request
	 * 
	 * @param response
	 * 
	 * @param ids[]
	 */
	@RequestMapping("deleteRole")
	public void deleteRole(HttpServletRequest request,
			HttpServletResponse response) {
		ResponseInfo responseInfo = new ResponseInfo();
		RequestContext requestContext = new RequestContext(request);
		HttpSession session = request.getSession();
		/* 接收前端传输的id值 */
		String[] ids = request.getParameterValues("ids[]");
		if (ids != null) {
			/* 执行删除操作 */
			int dels = roleService.deletes(ids);
			if (dels == 0){
				responseInfo.setResult("00021");
				responseInfo.setMessage(requestContext
						.getMessage("delete.fail"));
			}else if(dels == 2) {
				responseInfo.setResult("00022");
				responseInfo.setMessage(requestContext
						.getMessage("role.existing.staff"));
			} else {
				responseInfo.setResult("00020");
				responseInfo.setMessage(requestContext
						.getMessage("delete.success"));
			}
		} else {
			responseInfo.setResult("00021");
			responseInfo.setMessage(requestContext.getMessage("delete.fail"));
		}
		WebUtil.responseToJson(response, responseInfo);
	}

	/*
	 * 根据角色ID查看该角色下的用户ID
	 * 
	 * @param sysRole
	 * 
	 * @param request
	 * 
	 * @param response
	 */
	@RequestMapping("selectRoleUsers")
	public void selectRoleUsers(SysRole sysRole, HttpServletRequest request,
			HttpServletResponse response) {
		RequestContext requestContext = new RequestContext(request);
		ResponseInfo responseInfo = new ResponseInfo();
		List<SysUser> usersList = new ArrayList<SysUser>();
		List userIds = new ArrayList();
		/* 获取前端传入的id,判断是否为null */
		if (sysRole.getId() != null) {
			/* 根据角色ID查看该角色下的用户ID */
			usersList = roleService.findUsers(sysRole);
			for (int i = 0; i < usersList.size(); i++) {
				userIds.add(usersList.get(i).getUserId());
			}
			responseInfo.setResult("00010");
			responseInfo
					.setMessage(requestContext.getMessage("select.success"));
		} else {
			responseInfo.setResult("00011");
			responseInfo.setMessage(requestContext.getMessage("select.fail"));
		}
		responseInfo.setObject(userIds);
		WebUtil.responseToJson(response, responseInfo);
	}

	/*
	 * 角色下添加用户
	 * 
	 * @param request
	 * 
	 * @param response
	 */
	@RequestMapping("addRoleUsers")
	public void addRoleUsers(HttpServletRequest request,
			HttpServletResponse response) {
		SysUser sysUser = new SysUser();
		RequestContext requestContext = new RequestContext(request);
		ResponseInfo responseInfo = new ResponseInfo();
		/* 前端传入的角色ID和用户ID */
		String roleId = request.getParameter("roleId");
		String[] userIds = request.getParameterValues("userIds[]");
		sysUser.setRoleId(roleId);
		sysUser.setUserIds(userIds);
		int flag = roleService.insertRoleUsers(sysUser);
		if (flag != 0) {
			responseInfo.setResult("00040");
			responseInfo.setMessage(requestContext.getMessage("add.success"));
		} else {
			responseInfo.setResult("00041");
			responseInfo.setMessage(requestContext.getMessage("add.fail"));
		}
		WebUtil.responseToJson(response, responseInfo);
	}
	
	/*
	 * 根据角色名roleName查询是否有重复角色
	 * 
	 * @param sysRole
	 * 
	 * @param request
	 * 
	 * @param response
	 */
	@RequestMapping("selectRoleName")
	public void selectRoleName(PagerModel pagerModel,SysRole sysRole, HttpServletRequest request,
			HttpServletResponse response) {
		RequestContext requestContext = new RequestContext(request);
		ResponseInfo responseInfo = new ResponseInfo();
		/* 获取前端传入的roleName,判断是否为null */
		if (sysRole.getRoleName() != null) {
			pagerModel = roleService.selectOne(sysRole);
			if(pagerModel!=null){
			responseInfo.setResult("10040");
			responseInfo.setMessage(requestContext.getMessage("data.repeat"));
			}else
			{
				responseInfo.setResult("10050");
				responseInfo.setMessage(requestContext.getMessage("data.norepeat"));
			}
		}else{
			responseInfo.setResult("10041");
			responseInfo.setMessage(requestContext.getMessage("data.receive.fail"));
		}
		WebUtil.responseToJson(response, responseInfo);
	}
}